module D {
    export class App{
        /** 用户基本信息 */
        public static userData:UserData;
        /** 桌子信息 */
        public static table:Table;
        /** 当前房价信息 */
        public static roomData:RoomData;
        /** 房间列表 */
        public static roomList:Array<RoomData>;
        /** 当前游戏场景 */
        public static gameView:V.GameView;
        /** 进度面板 */
        private static loadView:V.LoadView;
        /** 场景对象 */
        private static stage:egret.Stage;

        /** 初始化信息 */
        public static init(s:egret.Stage){
            App.userData = new UserData();
            App.table = new Table();
            App.gameView = null;
            App.loadView = new V.LoadView();
            App.stage = s;

            let ev:how.EventManager = how.EventManager.getInstance(null);
            ev.addEventListener(CMDConfig.GET_LOGIN_SUCCESS, App.userData.login, App.userData, 1);
            ev.addEventListener(CMDConfig.GET_ROOMLIST, App.getroomList, App, 1);
            ev.addEventListener(CMDConfig.GET_CHANGESERVER_SUCESS, App.roomEnter, App, 1);
            ev.addEventListener(CMDConfig.GET_PLAYER_ENTER, App.playerEnter, App, 1);
            ev.addEventListener(CMDConfig.GET_STATUS_CHANGE, App.playerStatus, App, 1);
            ev.addEventListener(CMDConfig.GET_IN_GAME_GOLD_CHANGE, App.table.playerScore, App.table, 1);
            ev.addEventListener(CMDConfig.GET_GAMECONFIG, App.table.gameConfig, App.table, 1);
            ev.addEventListener(CMDConfig.GET_GAMESTATUS, App.onSyncData, App, 1);
            ev.addEventListener(CMDConfig.GET_GAME, App.gameData, App, 1);

            RES.addEventListener(RES.ResourceEvent.GROUP_COMPLETE, App.onResComplete, App);
            RES.addEventListener(RES.ResourceEvent.GROUP_LOAD_ERROR, App.onResError, App);
            RES.addEventListener(RES.ResourceEvent.GROUP_PROGRESS, App.onResProgress, App);

            //添加MovieClip支持纹理的rotated
            // let fun = egret.MovieClip.prototype.$render;
            // egret.MovieClip.prototype.$render = function(){
            //     if(this["frames"][this["currentFrame"] - 1].rotated) this.$renderNode["rotated"] = true;
            //     else this.$renderNode["rotated"] = false;
            //     fun.call(this);
            // };
            //添加sheet纹理集支持rotated
            // RES.SheetAnalyzer.prototype["parseSpriteSheet"] = function (texture, data, name) {
            //     var frames = data.frames;
            //     if (!frames) {
            //         return null;
            //     }
            //     var spriteSheet = new egret.SpriteSheet(texture);
            //     var textureMap = this.textureMap;
            //     for (var subkey in frames) {
            //         var config = frames[subkey];

            //         var texture_1 = new egret.Texture();
            //         if (config.offX === void 0) { config.offX = 0; }
            //         if (config.offY === void 0) { config.offY = 0; }
            //         if (config.sourceW === void 0) {
            //             config.sourceW = config.offX + config.w;
            //         }
            //         if (config.sourceH === void 0) {
            //             config.sourceH = config.offY + config.h;
            //         }
            //         texture_1._bitmapData = spriteSheet.$texture._bitmapData;
            //         texture_1.$initData(spriteSheet["_bitmapX"] + config.x, spriteSheet["_bitmapY"] + config.y, config.w, config.h, config.offX, config.offY, config.sourceW, config.sourceH, spriteSheet.$texture._sourceWidth, spriteSheet.$texture._sourceHeight, config.rotated);
            //         spriteSheet._textureMap[subkey] = texture_1;

            //         if (config["scale9grid"]) {
            //             var str = config["scale9grid"];
            //             var list = str.split(",");
            //             texture_1["scale9Grid"] = new egret.Rectangle(parseInt(list[0]), parseInt(list[1]), parseInt(list[2]), parseInt(list[3]));
            //         }
            //         if (textureMap[subkey] == null) {
            //             textureMap[subkey] = texture_1;
            //             if (name) {
            //                 this.addSubkey(subkey, name);
            //             }
            //         }
            //     }
            //     return spriteSheet;
            // };
            // let Ifun = eui.Image.prototype["parseSource"];
            // eui.Image.prototype["parseSource"] = function(){
            //     Ifun.call(this);
            //     if(this.texture) this.$renderNode["rotated"] = this.texture.$rotated;
            // }
        }

        /** 资源为加载完的临时对象 */
        private static sc:any;
        /** 需要加载的资源数组 */
        private static res:string[];
        /** 切换场景 */
        public static enterGame(scene:any):void{
            // for(let i=0;scene.Res && i<scene.Res.length;i++){
            //     await RES.loadGroup(scene.Res[i]);
            // }
            App.res = scene.Res.slice();
            App.sc = scene;
            App.loadView.setResNum(App.res.length);
            App.loadRes();
        }

        /** 资源加载完成 */
        public static onResComplete(e:RES.ResourceEvent):void{
            console.log("onResComplete", e.groupName);
            App.loadRes();
        }
        /** 加载资源 */
        public static loadRes():void{
            if(!App.sc) return;
            App.stage.addChild(App.loadView);
            App.loadView.update(0, 100);
            if(App.res && App.res.length){
                RES.loadGroup(App.res.shift());
            }else{
                how.Application.changeScene(App.sc);
                App.stage.removeChild(App.loadView);
                App.sc = null;
                if (D.App.userData.userStatus != UserStatus.PLAY && D.App.userData.userStatus != UserStatus.LOOKON) 
                { 

                    let data = {
                        wTableID: 0,
                        wChairID: 65535,
                        szTablePass: AppData.getInstance().currentRoom.szTablePass,
                        cbPassLen: AppData.getInstance().currentRoom.cbPassLen,
                        CellScore: AppData.getInstance().currentRoom.cellScore,
                        PreScore: AppData.getInstance().currentRoom.preScore,
                        };
                    if(AppData.getInstance().cardRoomData)
                    {
                       data.szTablePass = AppData.getInstance().cardRoomData.key.toString();
                    }
                     WebSocketInstance.getHallSocket().send(CMDConfig.SEND_SIT, data);
                } 
                else 
                {   
                    //同步牌桌信息
                    WebSocketInstance.getHallSocket().send(CMDConfig.SEND_SYNTABLE, { bAllowLookon: 1 });
                }
            }
        }

        /** 资源加载错误 */
        public static onResError(e:RES.ResourceEvent):void{
            console.log("onResError", e.groupName, e.itemsLoaded, e.itemsTotal);
            App.loadRes();
        }

        /** 资源加载进度 */
        public static onResProgress(e:RES.ResourceEvent):void{
            App.loadView.update(e.itemsLoaded, e.itemsTotal);
        }

        /** 接收到房间列表 */
        public static getroomList(e:egret.Event):void{
            let d = e.data;
            App.roomList = [];
            for(let i=0;i<d.wKindID.length;i++){
                let r = new RoomData();
                r.kindID = d.wKindID[i];
                r.serverID = d.wServerID[i];
                r.roomType = d.T[i];
                r.name = d.szServerName[i];
                r.baseScore = d.lBaseScore[i];
                r.limitScore = d.lLimitScore[i];
                r.cellScore = d.lCellScore[i];
                App.roomList.push(r);
            }
        }

        /** 进入房间 */
        public static roomEnter(e:egret.Event):void{
            let or:RoomData = App.roomData;
            App.roomData = null;
            for(let i=0;i<App.roomList.length;i++){
                if(App.roomList[i].serverID == e.data.port){
                    App.roomData = App.roomList[i];
                    break;
                }
            }
            if(App.roomData == null && or){
                how.module.ModuleManager.getInstance().initModule(MainSceneModule, MainSceneView);
            }
        }

        /** 玩家进入 */
        public static playerEnter(e:egret.Event):void{
            let c = App.table.playerEnter(e);
            App.gameView && App.gameView.showPlayer(c);
        }

        /** 玩家状态变化 */
        public static playerStatus(e:egret.Event):void{
            let c = App.table.playerStatus(e); //console.log("playerStatus", c);
            if(App.userData.userStatus == UserStatus.NULL){
                if(App.gameView) App.gameView.onDestroy();
                App.gameView = null;
                WebSocketInstance.getHallSocket().send(CMDConfig.SEND_CHANGESERVER, {});
            } else if(App.gameView){
                if(App.table.players[c]){
                    let s = App.gameView.c2p(c);
                    App.gameView.playerList[s] && App.gameView.playerList[s].status();
                }else App.gameView.showPlayer(c);
            }
        }

        /** 同步桌子数据 */
        public static onSyncData(e:egret.Event):void{
            App.gameView && App.gameView.onSyncData(e.data);
        }

        /** 游戏消息 */
        public static gameData(e:egret.Event):void{
            if(App.gameView) App.gameView.onNetData(e.data.s, e.data.d);
        }

        /** 二进制到json对象 */
        public static b2j(d:egret.ByteArray, m:any):any{
            let json = {};
            for(let i=0;i<m.length;i++){
                if(m[i][0] == "B"){
                    json[m[i][1]] = d.readUnsignedByte();
                }else if(m[i][0] == "S"){
                    json[m[i][1]] = d.readUnsignedShort();
                }else if(m[i][0] == "I"){
                    json[m[i][1]] = d.readUnsignedInt();
                }else if(m[i][0] == "L"){
                    json[m[i][1]] = d.readInt();
                    d.readInt();
                    //json[m[i][1]] += (d.readInt()<<32);
                }else if(m[i][0] == "A"){
                    json[m[i][1]] = [];
                    for(let j=0;j<m[i][2];j++){
                        if(m[i][3] == "B"){
                            json[m[i][1]][j] = d.readUnsignedByte();
                        }else if(m[i][3] == "S"){
                            json[m[i][1]][j] = d.readUnsignedShort();
                        }else if(m[i][3] == "I"){
                            json[m[i][1]][j] = d.readUnsignedInt();
                        }else if(m[i][3] == "L"){
                            json[m[i][1]][j] = d.readInt();
                            d.readInt();
                            //json[m[i][1]][j] += (d.readInt()<<32);
                        }else if(m[i][3] == "A"){
                            json[m[i][1]][j] = [];
                            for(let n=0;n<m[i][4];n++){
                                if(m[i][5] == "B"){
                                    json[m[i][1]][j][n] = d.readUnsignedByte();
                                }else if(m[i][5] == "S"){
                                    json[m[i][1]][j][n] = d.readUnsignedShort();
                                }else if(m[i][5] == "I"){
                                    json[m[i][1]][j][n] = d.readUnsignedInt();
                                }else if(m[i][5] == "L"){
                                    json[m[i][1]][j][n] = d.readInt();
                                    d.readInt();
                                    //json[m[i][1]][j][n] += (d.readInt()<<32);
                                }
                            }
                        }
                    }
                }
            }
            return json;
        }
    }
}